﻿''' <summary>
''' This is a helper class to access our WebService, It must stay with SystemBoxExpress project, cause the reference to the webservice is attache with.
''' </summary>
''' <remarks></remarks>
Public Class SystemBoxWSvc
    ''' <summary>
    ''' Connect to SystemBoxWebService
    ''' Refer to the app.config file
    ''' ------- Your a not suposed to change this function when the app.config is properly configured  ------
    ''' aleblanc - 2012-01-13
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks>For now BasicHttpBinding is define under the name "BasicHttpBinding_ISystemBox" 
    '''          With Windows Authentication we will need to define a new Binding section in the Bindings Section
    '''          Then change the Client Section to use the appropriate binding.
    ''' 
    '''          Basic authentication is supported.
    '''          
    '''          ------- Your a not suposed to change this function when the app.config is properly configured  ------.
    '''</remarks>
    Public Shared Function Connect() As SBSvc.SystemBoxClient

        Using appOpt As MetaApplication = New MetaApplication("SystemBox")
            Dim ea As New System.ServiceModel.EndpointAddress(appOpt.MetaApplicationOptions("WebserviceAddress").DfltOptionValue)
            Dim newClient As SBSvc.SystemBoxClient = New SBSvc.SystemBoxClient()
            newClient.Endpoint.Address = ea

            If TypeOf (newClient.Endpoint.Binding) Is System.ServiceModel.BasicHttpBinding Then
                If CType(newClient.Endpoint.Binding, System.ServiceModel.BasicHttpBinding).Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Basic Then
                    '
                    newClient.ClientCredentials.UserName.UserName = MetaValue.GetMetaValueByCode("OPT_BASIC_AUTHENTICATION_USER").Value
                    newClient.ClientCredentials.UserName.Password = MetaValue.GetMetaValueByCode("OPT_BASIC_AUTHENTICATION_PWD").Value
                    '
                    'newClient.ClientCredentials.UserName.UserName = "SystemBoxWSVC@Scief.com"
                    'newClient.ClientCredentials.UserName.Password = "@1x2x3xX@"
                End If
            End If
            Return newClient
        End Using
    End Function


    ''' <summary>
    ''' This fonction is use to send/process InventoryBatch on our WebService
    ''' </summary>
    ''' <param name="aDataRow"></param>
    ''' <returns></returns>
    ''' <remarks>For now we need to change the code if we want to bypass SCIEF WSVC</remarks>
    Public Overridable Function ProcessBatch(ByVal aDataRow As DataRow) As Boolean
        Dim clientSvc As SBSvc.SystemBoxClient = Nothing

        If aDataRow.Table.DataSet IsNot Nothing AndAlso aDataRow.Table.DataSet.HasChanges Then
            'TODO: To Translate...
            'OutStandingIssue: Automatiser le Save pour les Actions...
            Throw New Exception("Please save your changes, action canceled")
            Return False
        End If

        If aDataRow IsNot Nothing Then
            Try
                clientSvc = SystemBoxWSvc.Connect()
                Dim status As Guid = CType(aDataRow("StatusID_FK"), Guid)
                If status = IdRepository.APP_TRANSTATUS_OPEN Or status = IdRepository.APP_TRANSTATUS_PDG Or status = IdRepository.APP_TRANSTATUS_PROC Then
                    Dim invBatchID As Guid = New Guid(aDataRow("InvBatchID").ToString)
                    If clientSvc.ProcessInventoryBatch(invBatchID) Then
                        Throw New Exception("Inventory Batch Has Been Process. Make Sure Batch Status is Released")
                    Else
                        Throw New Exception("Inventory Batch Can't be Process. Check Batch Status")
                    End If
                Else
                    Throw New Exception("Inventory Batch Can't be Process. Status must be Open or Pending or Processing")
                End If
            Finally
                If clientSvc IsNot Nothing Then
                    clientSvc.Close()
                End If
            End Try
        End If
        Return True
    End Function

    ''' <summary>
    ''' This fonction is use to send/process InventoryBatch on our WebService
    ''' </summary>
    ''' <param name="aDataRow"></param>
    ''' <returns></returns>
    ''' <remarks>For now we need to change the code if we want to bypass SCIEF WSVC</remarks>
    Public Overridable Function ProcessPO(ByVal aDataRow As DataRow) As Boolean
        Dim clientSvc As SBSvc.SystemBoxClient = Nothing

        If aDataRow.Table.DataSet IsNot Nothing AndAlso aDataRow.Table.DataSet.HasChanges Then
            'TODO: To Translate...
            'OutStandingIssue: Automatiser le Save pour les Actions...
            Throw New Exception("Please save your changes, action canceled")
            Return False
        End If

        If aDataRow IsNot Nothing Then
            Try
                clientSvc = SystemBoxWSvc.Connect()
                'Dim status As Guid = CType(aDataRow("StatusID_FK"), Guid)
                'If status = IdRepository.APP_TRANSTATUS_OPEN Or status = IdRepository.APP_TRANSTATUS_PDG Or status = IdRepository.APP_TRANSTATUS_PROC Then
                Dim invBatchID As Guid = New Guid(aDataRow("InvBatchID").ToString)

                'Process de toutes les lignes RELEASE
                If clientSvc.ProcessInventoryBatch(invBatchID) Then
                    'If clientSvc.ProcessInventoryBatchWithWhere(invBatchID, " LotTransaction.StatusID_FK = 'F73A327F-CCB0-4888-9F3F-FFD5B51A647E' ") Then
                    Throw New Exception("PO Has Been Process. Make Sure PO Status is Released or Transmited")
                Else
                    Throw New Exception("PO Can't be Process. Check PO Status")
                End If
            Finally
                If clientSvc IsNot Nothing Then
                    clientSvc.Close()
                End If
            End Try
        End If
        Return True
    End Function

    ''' <summary>
    ''' This fonction is use to send/process InventoryBatch Transaction on our WebService
    ''' </summary>
    ''' <param name="aDataRow"></param>
    ''' <returns></returns>
    ''' <remarks>For now we need to change the code if we want to bypass SCIEF WSVC</remarks>
    Public Overridable Function ProcessBatchTransaction(ByVal aDataRow As DataRow) As Boolean
        Dim clientSvc As SBSvc.SystemBoxClient = Nothing

        If aDataRow.Table.DataSet IsNot Nothing AndAlso aDataRow.Table.DataSet.HasChanges Then
            'TODO: To Translate...
            'OutStandingIssue: Automatiser le Save pour les Actions...
            Throw New Exception("Please save your changes, action canceled")
            Return False
        End If

        If aDataRow IsNot Nothing Then
            Try
                clientSvc = SystemBoxWSvc.Connect()
                Dim status As Guid = CType(aDataRow("StatusID_FK"), Guid)
                If status = IdRepository.APP_TRANSTATUS_OPEN Or status = IdRepository.APP_TRANSTATUS_PDG Then
                    Dim lotTranId As Guid = New Guid(aDataRow("LotTranID").ToString)
                    If clientSvc.ProcessBatchTransaction(lotTranId) Then
                        'If LotTransaction_PL.ProcessBatchTransaction(lotTranId) Then Pas de WS
                        Throw New Exception("Inventory Batch Line Has Been Process. Make Sure Batch Line Status is Released")
                    Else
                        Throw New Exception("Inventory Batch Line Can't be Process. Check Batch Line Status")
                    End If
                Else
                    Throw New Exception("Inventory Batch Line Can't be Process. Status must be Open or Pending")
                End If
            Finally
                If clientSvc IsNot Nothing Then
                    clientSvc.Close()
                End If
            End Try
        End If
        Return True
    End Function

    ''' <summary>
    ''' This fonction is use to send/process InventoryBatch Transaction on our WebService
    ''' </summary>
    ''' <param name="aDataRow"></param>
    ''' <returns></returns>
    ''' <remarks>For now we need to change the code if we want to bypass SCIEF WSVC</remarks>
    Public Overridable Function ProcessPOTransaction(ByVal aDataRow As DataRow) As Boolean
        Dim clientSvc As SBSvc.SystemBoxClient = Nothing
        Dim errormsg As String = Nothing
        Dim processLEMS As Boolean = True

        If aDataRow.Table.DataSet IsNot Nothing AndAlso aDataRow.Table.DataSet.HasChanges Then
            'TODO: To Translate...
            'OutStandingIssue: Automatiser le Save pour les Actions...
            Throw New Exception("Please save your changes, action canceled")
            Return False
        End If

        If aDataRow IsNot Nothing Then
            Try
                clientSvc = SystemBoxWSvc.Connect()
                Dim status As Guid = CType(aDataRow("StatusID_FK"), Guid)
                If status = IdRepository.APP_TRANSTATUS_OPEN Or status = IdRepository.APP_TRANSTATUS_PDG Then
                    Dim lotTranId As Guid = New Guid(aDataRow("LotTranID").ToString)
                    'OutStandingIssue: A faire completement du coté WS - AL / 2012-09-19
                    If LotTransaction_PL.ProcessBatchTransaction(lotTranId) Then
                        If String.IsNullOrWhiteSpace(errormsg) Then
                            processLEMS = MESSDK.LotTransaction_PL.SetTransactionStatus(lotTranId, SCIEF.ActiveFramework.CommonExt.Base.IdRepository.APP_TRANSTATUS_REL, SCIEF.ActiveFramework.CommonExt.Base.IdRepository.APP_TRANSTATUS_TRANS)
                            Throw New Exception("PO Line Has Been Process. Make Sure Batch Line Status is Released or Transmited")
                        Else
                            Throw New Exception(errormsg)
                        End If
                    Else
                        Throw New Exception("PO Line Can't be Process. Check Batch Line Status")
                    End If
                Else
                    Throw New Exception("PO Line Can't be Process. Status must be Open or Pending")
                End If
            Finally
                If clientSvc IsNot Nothing Then
                    clientSvc.Close()
                End If
            End Try
        End If
        Return True
    End Function

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="aDataRow"></param>
    ''' <remarks></remarks>
    Public Overridable Function GenerateInventorySheet(ByVal aDataRow As DataRow) As Boolean

        Dim clientSvc As SBSvc.SystemBoxClient = Nothing

        If aDataRow.Table.DataSet IsNot Nothing AndAlso aDataRow.Table.DataSet.HasChanges Then
            'TODO: To Translate...
            'OutStandingIssue: Automatiser le Save pour les Actions...
            Throw New Exception("Please save your changes, action canceled")
            Return False
        End If

        Try
            clientSvc = SystemBoxWSvc.Connect()
            Dim invCountId As Guid = New Guid(aDataRow("InvCountId").ToString)
            If clientSvc.GenerateInventorySheet(invCountId) Then
                Throw New Exception("Inventory Sheet Generated")
            End If

            Return True
        Finally
            If clientSvc IsNot Nothing Then
                clientSvc.Close()
            End If
        End Try
        Return False
    End Function

    Public Overridable Function GenerateInventoryBatch(ByVal aDataRow As DataRow) As Boolean
        Dim clientSvc As SBSvc.SystemBoxClient = Nothing

        If aDataRow.Table.DataSet IsNot Nothing AndAlso aDataRow.Table.DataSet.HasChanges Then
            'TODO: To Translate...
            'OutStandingIssue: Automatiser le Save pour les Actions...
            Throw New Exception("Please save your changes, action canceled")
            Return False
        End If

        Try
            clientSvc = SystemBoxWSvc.Connect()
            '
            Dim invCountId As Guid = New Guid(aDataRow("InvCountId").ToString)
            '
            'OutStandingIssue: Valider que la batch n'est pas déja faite... pour reseter et en faire une nouvelle  aleblanc - 2011/07/13
            If clientSvc.GenerateInventoryBatch(invCountId) Then
                Throw New Exception("Inventory Batch Generated")
            End If
            Return True
        Finally
            If clientSvc IsNot Nothing Then
                clientSvc.Close()
            End If
        End Try
        Return False
    End Function

    Public Overridable Function ChangeLotStatus(ByVal aMetaDataTable As MetaDataTable) As Boolean
        Dim clientSvc As SBSvc.SystemBoxClient = Nothing
        Dim aDataSet As DataSet = New DataSet

        Try
            clientSvc = SystemBoxWSvc.Connect()
            aMetaDataTable.ApplyChanges(reload:=False)
            aDataSet.Tables.Add(aMetaDataTable)
            clientSvc.ChangeStatus(aDataSet)
            Return True
        Finally
            If clientSvc IsNot Nothing Then
                clientSvc.Close()
            End If
        End Try
        Return False
    End Function
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="configParam"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function TestNotificationConnection(ByRef configParam As PL.MetaSDK.Configuration_PL) As Boolean
        Dim clientSvc As SBSvc.SystemBoxClient = Nothing

        Try
            clientSvc = SystemBoxWSvc.Connect()
            'Commented because we don't know how to pass our sCIEF TYPES ConfigParam
            'Dim invCountId As Guid = New Guid(aDataRow("InvCountId").ToString)
            '
            'OutStandingIssue: Valider que la batch n'est pas déja faite... pour reseter et en faire une nouvelle  aleblanc - 2011/07/13
            'If clientSvc.TestNotificationMessage Then
            'Throw New Exception("Inventory Batch Generated")
            'End If
            ' clientSvc.TestNotificationConnection(configParam)
            Return True
        Finally
            If clientSvc IsNot Nothing Then
                clientSvc.Close()
            End If
        End Try
        Return False
    End Function

    Public Function ValidateLicense(ByVal CompanieId As Guid, ByRef msg As String) As Boolean
        Dim clientSvc As SBSvc.SystemBoxClient = Nothing
        Try
            clientSvc = SystemBoxWSvc.Connect()
            clientSvc.ValidateLicense(CompanieId, msg)

            Return True
        Finally
            If clientSvc IsNot Nothing Then
                clientSvc.Close()
            End If
        End Try
        Return False
    End Function

    Public Function Register(ByVal CompanieId As Guid, ByRef msg As String) As Boolean
        Dim clientSvc As SBSvc.SystemBoxClient = Nothing
        Try
            clientSvc = SystemBoxWSvc.Connect()

            clientSvc.Register(CompanieId, msg)

            Return True
        Finally
            If clientSvc IsNot Nothing Then
                clientSvc.Close()
            End If
        End Try
        Return False
    End Function

    Public Function ProductSave(ByVal aDataSet As DataSet, ByVal metaQueryName As String, ByRef returnedMessage As String) As Boolean
        Dim clientSvc As SBSvc.SystemBoxClient = Nothing
        Try
            clientSvc = SystemBoxWSvc.Connect()
            clientSvc.ProductSave(aDataSet, metaQueryName, returnedMessage)

            Return True
        Finally
            If clientSvc IsNot Nothing Then
                clientSvc.Close()
            End If
        End Try
        Return False
    End Function

    Public Function GetNextSequence(ByVal groupID As Guid, ByVal typeID As Guid, ByVal classID As Guid, ByVal categorieID As Guid) As String
        Dim clientSvc As SBSvc.SystemBoxClient = Nothing
        Dim strCode As String
        Try
            clientSvc = SystemBoxWSvc.Connect()
            strCode = clientSvc.GetNextSequence(groupID, typeID, classID, categorieID)
            Return strCode
        Finally
            If clientSvc IsNot Nothing Then
                clientSvc.Close()
            End If
        End Try
        Return strCode
    End Function


End Class
